<template>
	<div>
		<el-form ref="configForm" :model="form" :rules="rules" label-position="top">
			<div class="base-container">
				<p class="title">公钥证书上传</p>
				<div class="key-box" style="padding-bottom: 2px">
					<div class="flex items-center mb-8px">
						<span class="prefix">*</span>
						<p class="sub-title" style="margin-left: 0">发卡机构公钥证书</p>
					</div>

					<el-form-item label="" prop="upload">
						<el-upload
							ref="uploadRef"
							:limit="1"
							accept=".IG04"
							:headers="upload.headers"
							:data="{ id: flowId }"
							:action="upload.url + '?updateSupport=' + upload.updateSupport"
							:disabled="upload.isUploading"
							:before-upload="beforeUpload"
							:on-progress="handleFileUploadProgress"
							:on-success="handleFileSuccess"
							:on-remove="handleFileRemove"
							:on-change="handleChange"
							:auto-upload="false"
							drag
							style="width: 100%">
							<el-icon class="el-icon--upload"><upload-filled /></el-icon>
							<div class="el-upload__text">
								将文件拖到此处，或
								<em>点击上传</em>
							</div>
						</el-upload>
					</el-form-item>
				</div>

				<div class="key-box mt-10px" style="padding-bottom: 2px">
					<div class="flex items-center mb-8px">
						<span class="prefix">*</span>
						<p class="sub-title" style="margin-left: 0">根证书</p>
					</div>

					<el-form-item label="" prop="upload2">
						<el-upload
							ref="uploadRef2"
							:limit="1"
							accept=".JG04"
							:headers="upload2.headers"
							:data="{ id: flowId }"
							:action="upload2.url + '?updateSupport=' + upload2.updateSupport"
							:disabled="upload2.isUploading"
							:before-upload="beforeUpload2"
							:on-progress="handleFileUploadProgress2"
							:on-success="handleFileSuccess2"
							:on-remove="handleFileRemove2"
							:on-change="handleChange2"
							:auto-upload="false"
							drag
							style="width: 100%">
							<el-icon class="el-icon--upload"><upload-filled /></el-icon>
							<div class="el-upload__text">
								将文件拖到此处，或
								<em>点击上传</em>
							</div>
						</el-upload>
					</el-form-item>
				</div>
			</div>
		</el-form>

		<div style="height: 60px"></div>

		<div class="page-footer">
			<el-button @click="onCancel">上一步</el-button>
			<el-button type="primary" @click="onConfirm">完成</el-button>
		</div>
	</div>
</template>

<script setup>
import { getToken } from '@/utils/auth'

const route = useRoute()
const { proxy } = getCurrentInstance()

const emits = defineEmits(['cancel', 'confirm'])

const flowId = computed(() => {
	return Number(route.query.id) || null
})

const configForm = ref()
const form = ref({
	upload: '',
	upload2: ''
})
const rules = {
	upload: [{ required: true, message: '请上传发卡机构公钥证书' }],
	upload2: [{ required: true, message: '请上传根证书' }]
}

const uploadRef = ref()
const uploadRef2 = ref()

// 是否上传成功
const uploadSuccess = ref(false)
const uploadSuccess2 = ref(false)

// 发卡机构证书上传
const upload = reactive({
	// 是否禁用上传
	isUploading: false,
	// 是否更新已经存在的线路数据
	updateSupport: 0,
	// 设置上传的请求头部
	headers: { Authorization: 'Bearer ' + getToken() },
	// 上传的地址
	url: import.meta.env.VITE_APP_BASE_API + '/bus/codeManagementConfig/cardPubKeyCaUpload'
})

// 根证书上传
const upload2 = reactive({
	isUploading: false,
	updateSupport: 0,
	headers: { Authorization: 'Bearer ' + getToken() },
	url: import.meta.env.VITE_APP_BASE_API + '/bus/codeManagementConfig/rootCaUpload'
})

function isValidFileType(allowedExtension, file) {
	if (!allowedExtension || !file) return false
	const fileExtension = file.name.split('.').pop()
	return fileExtension.toUpperCase() === allowedExtension.toUpperCase()
}

/** 文件上传前处理 */
const beforeUpload = (file) => {
	const allowedExtension = 'IG04'
	if (!isValidFileType(allowedExtension, file)) {
		proxy.$modal.msgError('只允许上传 .IG04 文件')
		return false
	}
	return true
}

const beforeUpload2 = (file) => {
	const allowedExtension = 'JG04'
	if (!isValidFileType(allowedExtension, file)) {
		proxy.$modal.msgError('只允许上传 .JG04 文件')
		return false
	}
	return true
}

const handleChange = (file) => {
	if (file.status == 'ready') {
		form.value.upload = file.name
		configForm.value.validateField('upload')
	}
}

const handleChange2 = (file) => {
	if (file.status == 'ready') {
		form.value.upload2 = file.name
		configForm.value.validateField('upload2')
	}
}

/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
	upload.isUploading = true
}

const handleFileUploadProgress2 = (event, file, fileList) => {
	upload2.isUploading = true
}

/** 移除文件 */
const handleFileRemove = () => {
	form.value.upload = ''
}

const handleFileRemove2 = () => {
	form.value.upload2 = ''
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
	upload.isUploading = false
	if (response.code != 200) {
		uploadRef.value.handleRemove(file)
		proxy.$alert(
			"<div style='overflow: autooverflow-x: hiddenmax-height: 70vhpadding: 10px 20px 0'>" + response.msg + '</div>',
			'发卡机构公钥证书导入失败',
			{ dangerouslyUseHTMLString: true }
		)
	} else {
		uploadSuccess.value = true
		handleConfirm()
	}
}

const handleFileSuccess2 = (response, file, fileList) => {
	upload2.isUploading = false
	if (response.code != 200) {
		uploadRef2.value.handleRemove(file)
		proxy.$alert(
			"<div style='overflow: autooverflow-x: hiddenmax-height: 70vhpadding: 10px 20px 0'>" + response.msg + '</div>',
			'根证书导入失败',
			{ dangerouslyUseHTMLString: true }
		)
	} else {
		uploadSuccess2.value = true
		handleConfirm()
	}
}

const onCancel = () => {
	emits('cancel')
}

const onConfirm = () => {
	configForm.value.validate((valid) => {
		if (valid) {
			uploadRef.value.submit()
			uploadRef2.value.submit()
		}
	})
}

const handleConfirm = () => {
	if (uploadSuccess.value && uploadSuccess2.value) {
		emits('confirm')
	}
}
</script>

<style lang="scss" scoped>
@import './base.scss';
</style>
